package net.oschina.app.base;

import net.oschina.app.interf.Constants;
import net.oschina.app.myapp.MyApplication;
import net.oschina.app.service.ApiService;
import net.oschina.app.service.GsonService;
import net.oschina.app.util.CommonUtils;

import java.io.File;
import java.io.IOException;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;

/**
 * Created by wei03 on 2017/1/13.
 */

public abstract class BaseProtocol<T> {
    public ApiService mApiService;
    protected int mPageIndex = 0;
    protected int mPageSize = Constants.PAGESIZE;

    public int getPageIndex() {
        return mPageIndex;
    }

    public void setPageIndex(int pageIndex) {
        mPageIndex = pageIndex;
    }

    public int getPageSize() {
        return mPageSize;
    }

    public void setPageSize(int pageSize) {
        mPageSize = pageSize;
    }

    public void setPage(int pageIndex, int pageSize) {
        mPageIndex = pageIndex;
        mPageSize = pageSize;
    }

    public BaseProtocol() {
        initRetrofit();
    }

    private void initRetrofit() {
        if (mApiService == null) {
            mApiService = getApiService();
        }
    }

    public ApiService getApiService() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constants.HOST)
                .client(getClient())
                .addConverterFactory(SimpleXmlConverterFactory.create())
                .build();

        return MyApplication.mRetrofit.create(ApiService.class);
    }
    public GsonService getGsonService() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constants.HOST)
                .client(getClient())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        return retrofit.create(GsonService.class);
    }
    public T getData(int pageIndex) {
        Call<T> call = getCall(String.valueOf(pageIndex));
        try {
            T body = call.execute().body();
            return body;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public OkHttpClient getClient() {
        File httpCacheDirectory = new File(CommonUtils.getContext().getCacheDir(), "responses");
        //设置缓存 10M
        Cache cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);

        //创建OkHttpClient，并添加拦截器和缓存代码
        OkHttpClient client = new OkHttpClient.Builder()
                .cache(cache)
                .addInterceptor(mInterceptor)
                .build();
        return client;
    }


    Interceptor mInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (!CommonUtils.isNetworkReachable(CommonUtils.getContext())) {
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
            }

            Response response = chain.proceed(request);
            if (CommonUtils.isNetworkReachable(CommonUtils.getContext())) {
                int maxAge = 60 * 60; // read from cache for 1 minute
                response.newBuilder()
                        .removeHeader("Pragma")
                        .header("Cache-Control", "public, max-age=" + maxAge)
                        .build();
                System.out.println("aaaaa");
            } else {
                int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
                response.newBuilder()
                        .removeHeader("Pragma")
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                        .build();
                System.out.println("bbbb");
            }
            return response;
        }
    };


    protected abstract Call<T> getCall(String pageIndex);

    protected T parserDatas(String data) {
        return null;
    }

    protected String getIndex() {
        return "";
    }

    protected String getType() {
        return "";
    }
}
